package com.zan.service.job;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.zan.dao.OrderItemMapper;
import com.zan.dao.OrdersMapper;
import com.zan.dao.ProductSkuMapper;
import com.zan.entity.OrderItem;
import com.zan.entity.Orders;
import com.zan.entity.ProductSku;
import com.zan.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class OrderTimeoutCheckJob {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderService orderService;

    private WXPay wxPay = new WXPay(new MyPayConfig());


    @Scheduled(cron = "0/60 * * * * ?")
    public void checkAndCloseOrder() {
        try {
            System.out.println("----------定时任务----------");
            //1.查询超过30min订单状态依然为待支付的订单
            Example example = new Example(Orders.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("status", 1);
            Date time = new Date(System.currentTimeMillis() - 30 * 60 * 1000); //当前时间往前推送30分钟
            criteria.andLessThan("createTime", time); //如果比我当前时间再前30分钟还小，那就说明超时了
            List<Orders> orders = ordersMapper.selectByExample(example);

            //2 访问微信平台接口，与微信支付平台进行校对，看是否真的已经支付，还是会因为网络波动导致回调接口有误，查看订单最终的支付状态
            for (Orders order : orders) {
                HashMap<String, String> map = new HashMap<>();
                map.put("out_trade_no", order.getOrderId());
                Map<String, String> resp = wxPay.orderQuery(map);
                if ("SUCCESS".equalsIgnoreCase(resp.get("trade_state"))) {
                    //2.1 如果订单已经支付，则修改订单状态为“待发货/已支付” status = 2
                    Orders updateOrder = new Orders();
                    updateOrder.setOrderId(order.getOrderId());
                    updateOrder.setStatus("2");
                    int i = ordersMapper.updateByPrimaryKeySelective(updateOrder);

                } else if ("NOTPAY".equalsIgnoreCase(resp.get("trade_state"))) {
                    //2.2 确实未支付，取消订单
                    //2.2.1 向微信支付平台发送请求，关闭当前订单的支付链接
                    Map<String, String> closeResp = wxPay.closeOrder(map);
                    System.out.println(closeResp);
                    if ("SUCCESS".equalsIgnoreCase(closeResp.get("return_code"))) { //说明关闭了
                        //2.2.2 修改当前订单: status = 6 (订单已关闭)  close_type = 1 (关闭类型为超时未支付)
                        //关闭订单封装到serviceImpl中，为了添加事务
                        orderService.closeOrder(order.getOrderId());
                    }
                }
                System.out.println(resp);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
